<!--
 * @Description: 租户产品管理-首页 
 * @Author: 马山
 * @Date: 2020-03-30 15:36:26
 * @LastEditTime: 2020-04-07 15:14:46
 * @LastEditors: 黄勇
 -->

<template>
    <div class="tenantManage">
        <div class="tenantManage-content">
            <!-- 条件选择组件 -->
            <query-form :queryList="queryList" @submit="submit"></query-form>
            <!-- 增删改查按钮组 -->
            <div class="operate-content">
                <el-button @click="create" type="primary" size="mini">
                    <app-icon iconName="vcloud-btn-add"></app-icon>
                    新建单位产品
                </el-button>
                <el-button @click="revice" plain size="mini">
                    <app-icon iconName="vcloud-xiugai"></app-icon>
                    修改单位产品
                </el-button>
                <el-button @click="remove" plain size="mini" :disabled="hasProduct">
                    <app-icon iconName="vcloud-shanchu"></app-icon>
                    删除
                </el-button>
                <!-- <el-button @click="addTenantProduct" plain size="mini">
                    <app-icon iconName="vcloud-btn-add"></app-icon>
                    添加租户产品
                </el-button>
                <el-button @click="modifyTenantProduct" plain size="mini">
                    <app-icon iconName="vcloud-xiugai"></app-icon>
                    修改租户产品
                </el-button> -->
                <!-- <el-button @click="switchFun" plain size="mini">
                    <app-icon iconName="vcloud-switch"></app-icon>
                    停启用
                </el-button> -->
                <!-- <el-button @click="switchFun" plain icon="el-icon-message" size="mini">停启用</el-button> -->
            </div>
            <!-- 表格数据 -->
            <div class="tenant-table disabledCheckbox">
                <el-table
                    ref="singleTable"
                    :height="tableHeight()"
                    :data="tableData"
                    :row-class-name="setRowClassName"
                    header-row-class-name="header-row"
                    @selection-change="getCurrentRow"
                    @select=" ( selection , row ) => selectRowProduct(row)"
                    @row-click="selectRowProduct"
                    style="width: 100%">

                    <el-table-column
                    type="selection"
                    label="序号"
                    width="60">
                    </el-table-column>

                    <!-- 渲染表头  -->
                    <el-table-column
                        v-for='col in tableHeadData'
                        :fixed="col.title=='operation' ? 'right':false"
                        :show-overflow-tooltip=" true "
                        :width="columnWidth(col)"
                        :prop="col.title"
                        :label="col.text"
                        :key="col.title">
                        <!-- 自定义显示格式 -->
                        <template slot-scope="scope">
                            <!-- 产品状态 -->
                            <div v-if="col.title == 'productStatus' ">
                                <app-status v-if="scope.row[col.title]==0" :type="staticType.getStaticTypeLabel('appStatusType',2)" :text="'未启用'"></app-status>
                                <app-status v-else-if="scope.row[col.title]==1" :type="staticType.getStaticTypeLabel('appStatusType',1)" :text="'启用'"></app-status>
                                <app-status v-else-if="scope.row[col.title]==2" :type="staticType.getStaticTypeLabel('appStatusType',3)" :text="'过期停用'"></app-status>
                                <app-status v-else-if="scope.row[col.title]==3" :type="staticType.getStaticTypeLabel('appStatusType',3)" :text="'手动停用'"></app-status>
                            </div>
                            <!-- 类型 -->
                            <div v-else-if="col.title == 'unitProductType' ">
                                <p v-if="scope.row[col.title]==1">正式</p>
                                <p v-if="scope.row[col.title]==2">试用</p>
                            </div>
                            <!-- 产品详情 -->
                            <div v-else-if="col.title == 'productInfo' ">
                                <div v-if="scope.row[col.title]">
                                    <p>{{ scope.row[col.title].registerNumber + "," + scope.row[col.title].lifeTime}}</p>
                                    <p>{{ scope.row[col.title].spaceCapacity + "," + scope.row[col.title].products}}</p>
                                    <p>{{ scope.row[col.title].beginDate + "至" + scope.row[col.title].expireDate}}</p>
                                </div>
                            </div>
                            <!-- 操作 -->
                            <div v-else-if="col.title == 'operation' ">
                                <div class="viewDetail" @click="openDetail(scope.$index, scope.row)">
                                    <p :class="[{disabled_text:!scope.row['unitProductCode']}]">单位产品详情</p>
                                </div>
                            </div>
                            <!-- 默认文本样式 -->
                            <span v-else>
                                <!-- <i class="el-icon-time"></i> -->
                                <span>{{ scope.row[col.title] }}</span>
                            </span>
                        </template>
                    </el-table-column>

                </el-table>
            </div>

            <!-- 分页插件 -->
            <div v-if="paginationShow">
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    @prev-click="prevClick"
                    @next-click="nextClick"
                    :current-page="1"
                    :page-sizes="pageSizes"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
                </el-pagination>
            </div>
            <!-- 查看详情弹出框 -->
            <div class="detailDialog"><DetailDialog ref="detailDialog"></DetailDialog></div>
            <!-- 打开新建或修改详情弹出框 -->
            <ModifyDialog ref="modifyDetailDialog" @tenantCallback="tenantCallback"></ModifyDialog>
        </div>
    </div>
</template>

<script>
import QueryForm from "@/components/query.vue";
import DetailDialog from "./components/detailDialog.vue"; //查看详情弹出框
import ModifyDialog from "./components/modifyDialog.vue"; //新建或修改弹出框
import AppStatus from "@/components/AppCommon/AppStatus";
import {totalPageSize, totalPageSizes} from "../../utils/tool";

export default {
    name: "tenant-page",
    components: {
        QueryForm,
        DetailDialog,
        ModifyDialog,
        AppStatus
    },
    computed: {},
    data: () => ({

        // 条件选择组数据
        queryList:[
            {
                type:"text",
                title:"单位名称",
                value:"",
                key:"unitName"
            },{
                type:"text",
                title:"单位产品名称",
                value:"",
                key:"unitProductName"
            },{
                type:"select",
                title:"单位产品状态",
                value:"",
                key:"productStatus",
                options:[
                    {value:"",label:"全部"},
                    {value:"0",label:"未启用"},
                    {value:"1",label:"启动"},
                    {value:"2",label:"过期停用"},
                    {value:"3",label:"手动停用"}
                ]
            },{
                type:"text",
                title:"产品名称",
                value:"",
                key:"mainProductName"
            },{
                type:"date",//dateTime
                title:"生效日期",
                value:"", //["2020-10-04","2020-10-09"]
                key:"beginPeriod",
                group:true
            },{
                type:"date",
                title:"失效日期",
                value:"", //["2020-10-04","2020-10-09"]
                key:"expirePeriod",
                group:true
            }
        ],
        //查询条件记录
        queryCondition:{ 
            unitName:"", //单位名称
            unitProductName:"",//单位产品名称
            productStatus:"",  //租户产品状态-默认全部 1.启用 2.过期停用 3.手动停用
            mainProductName:"",//产品名称
            beginPeriod:"", //生效日期
            expirePeriod:""  //失效日期
        },
        // 表头列数据
        tableHeadData:[
            {
                title:"unitName",
                text:"单位名称"
            },{
                title:"unitId",
                text:"单位ID"
            },
            {
                title:"unitProductType",
                text:"类型"
            },
            {
                title:"unitProductCode",
                text:"单位产品编号"
            },{
                title:"unitProductName",
                text:"单位产品名称"
            },{
                title:"unitOrgCode",
                text:"单位产品码"
            },{
                title:"productName",
                text:"产品名称"
            },{
                title:"productCode",
                text:"产品编号"
            },
            // {
            //     title:"productInfo",
            //     text:"产品详情"
            // },
            {
                title:"productStatus",
                text:"单位产品状态"
            },{
                title:"beginPeriod",
                text:"生效时间"
            },{
                title:"expirePeriod",
                text:"失效时间"
            },{
                title:"operation",
                text:"操作"
            }
        ],
        tableData:[], //表格所有行数据
        currentRow:"", //选择的当前行的数据
        markRowSelect:{},
        hasProduct:false,//标记是否有产品数据了

        // 分页插件----
        paginationShow:true,
        pageSizes:totalPageSizes, //下拉动态设置当前页数
        pageSize:totalPageSize,    //当前页显示多少条数据 默认10条
        pageNum:1, //当前页
        total:0, //总条目数
    }),
    created() {
        
    },
    mounted() { //页面初始化
        this.getTenantData();
    },
    watch: {},
    methods: {
        
        //监听查询条件回调
        submit(data){
            console.log(data);
            data.forEach( item =>{ //设置查询条件
                switch(item.key){
                    case "unitName" :
                        this.queryCondition.unitName = item.value;
                        break;
                    case "unitProductCode" :
                        this.queryCondition.unitProductCode = item.value;
                        break;
                    case "unitProductName" :
                        this.queryCondition.unitProductName = item.value;
                        break;
                    case "productStatus" :
                        this.queryCondition.productStatus = item.value;
                        this.queryCondition.status = item.value;
                        break;
                    case "mainProductName" :
                        this.queryCondition.mainProductName = item.value;
                        break;
                    case "beginPeriod" :
                        this.queryCondition.beginPeriod = item.value ? item.value : "";
                        break;
                    case "expirePeriod" :
                        this.queryCondition.expirePeriod = item.value ? item.value : "";
                        break;
                }
            });
            this.pageNum = 1;
            this.getTenantData();
            this.paginationShow = false;
            this.$nextTick( () =>{
                this.paginationShow = true;
            });
        },
        //新建按钮
        create(){
            let data = {
                isCreate:true,
                unitData:{
                    orderCode:"",
                    unitName:"",
                    unitId:"",
                    unitProductCode:"",
                    unitProductType:"1",  //暂时隐藏单位产品类型
                    unitProductName:"",
                    productCode:"",
                    productName:"",
                    productInfo:"",
                    productStatus:"1"
                },
                title:"添加单位产品信息"
            }
            this.$refs.modifyDetailDialog.open(data);
        },
        //修改按钮
        revice(){
            if(!this.checkRowData(true))return;
            // console.log(this.currentRow);
            let data = {
                isCreate:false,
                unitData:this.currentRow[0],
                title:"修改单位产品信息"
            }
            this.$refs.modifyDetailDialog.open(data);
        },
        //删除按钮
        remove(){
            if(!this.checkRowData(true))return;
            this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.removeTenantItem();
            }).catch(() => {

            });
        },
        //删除数据接口
        removeTenantItem(){
            let ids = [];
            this.currentRow.forEach(item =>{
                ids.push(item.id);
            });
            this.api.deleteUnitProduct(
                {
                    id:this.currentRow[0].id  //单位产品编号来删除
                },{loading:true}
            ).then(res =>{
                console.log(res);
                // this.clearSelection(); //清空选择
                this.pageNum = 1;
                this.getTenantData(); //重新获取数据
            }).catch(err =>{
                console.log(err);
                this.$alert(err.data || err);
            });
        },
        // 监听新建/修改回调
        tenantCallback(data){
            console.log(data);
            let currentIndex = this.currentRow[0] ? this.currentRow[0].currentIndex :null;
             //新建/修改回调
            if(data.isCreate){ //新建
                this.pageNum = 1;
                this.getTenantData();
            }else{ //修改
                //目前只会修改租户名称和单位ID，所以只刷新这两项
                if(data.unitData){
                    this.tableData[currentIndex].unitProductType = data.unitData.unitProductType;
                    this.tableData[currentIndex].unitProductName = data.unitData.unitProductName;
                }
            }
            this.$refs.modifyDetailDialog.closeDialog();
            this.clearSelection(); //清空选择
        },
        // 表格处理------------------------

        // 获取表格数据
        getTenantData(){
            this.api.getunitProductList(
                {
                    pageNum:this.pageNum,
                    pageSize:this.pageSize,
                    ...this.queryCondition
                },{loading:true}
            ).then(res =>{
                console.log(res);
                let data = res.data;
                if(!data){
                    this.tableData = []; //以防接口如果突然挂了,结果还显示的原来的数据
                    return;
                }
                let listData = data.records;
                if(!listData || listData.length==0){
                    this.tableData = [];
                    return;
                }
                this.total = data.totalCount;
                let dataArray = [];
                listData.forEach( item =>{
                    let obj = {
                            id:item.id, //当前数据标记
                            unitName: item.unitName, //单位名称
                            unitId: item.unitId,  //单位ID
                            unitProductType:item.unitProductType,//单位产品类型
                            unitProductName:item.unitProductName,//单位产品名称
                            unitProductCode:item.unitProductCode,//单位产品编号
                            productName:item.productName,   //产品名称
                            productCode:item.productCode,   //产品编号
                            productStatus:item.productStatus,   //单位产品状态
                            unitOrgCode:item.unitOrgCode, //单位产品码
                            beginPeriod:this.formatTime(item.beginDate), //生效时间
                            expirePeriod:this.formatTime(item.expireDate),//失效时间
                            operation:""//操作
                        };
                    dataArray.push(obj);
                });
                this.tableData = dataArray;
            }).catch(err =>{
                // console.log(err);
                // 5.8 hy
                //this.$alert(err.data || err);
            });
        },
        //打开产品详情
        openDetail(index, row){
            if(!row.unitProductCode){
                // this.$alert("当前数据无产品详情。");
                return;
            }
            this.$refs.detailDialog.open(row);
        },




        // 其他操作-------------------

        //清空所有选择
        clearSelection(){
            this.$refs.singleTable.clearSelection(); 
        },
        //获取当前选中行
        getCurrentRow(val) {
            this.currentRow = val;
        },
        //行点击事件
        selectRowProduct(row, event, column) {
            this.$refs.singleTable.clearSelection();
            if ( this.markRowSelect && this.markRowSelect.unitProductCode === row.unitProductCode ) {
                this.markRowSelect = {};
                this.$refs.singleTable.setCurrentRow();
            } else {
                this.markRowSelect = row;
                this.$refs.singleTable.setCurrentRow(row);
                this.$refs.singleTable.toggleRowSelection(row);
                this.hasProduct = row.productCode ? true : false;
            }
        },
        //设置行class
        setRowClassName({row, column, rowIndex, columnIndex}){
            row.currentIndex = rowIndex; //手动给每个行设置一个索引
        },

        // 分页插件-----------------
        handleSizeChange(val) { //pageSize 改变时会触发
            console.log(`每页 ${val} 条`);
            this.pageSize = val;
            this.pageNum = 1;
            this.getTenantData();
            this.paginationShow = false;
            this.$nextTick( () =>{
                this.paginationShow = true;
            });
        },
        handleCurrentChange(val) { //pageNum 改变时会触发
            console.log(`当前页: ${val}`);
            this.pageNum = val;
            this.getTenantData();
        },
        prevClick(val){  //用户点击上一页按钮改变当前页后触发
            console.log(`上一页: ${val}`);
            this.pageNum = val;
            this.getTenantData();
        },
        nextClick(val){ //用户点击下一页按钮改变当前页后触发
            console.log(`下一页: ${val}`);
            this.pageNum = val;
            this.getTenantData(); 
        },
        // 校验是否选择了数据
        checkRowData(del){
            let currentRow = this.currentRow;
            if(!currentRow || currentRow.length == 0 ){
                this.$message("未选择任何数据！");
                return false;
            }
            if(!del && currentRow.length > 1){
                this.$message("只能选择一条数据！");
                return false;
            }
            return true;
        },
        //动态设置下表格高度
        tableHeight(){
            let windowH = document.body.offsetHeight;
            let height = windowH - 290;
            return height;
        },
        //手动设置一下列宽
        columnWidth(col){
            let mainContentW = document.body.offsetWidth - 200;
            let width = 50;
            switch (col.title){
                case "unitName": //租户名称
                    width = mainContentW / 5;
                    break;
                case "unitId": //单位ID
                    width = mainContentW / 7;
                    break;
                case "unitProductType"://单位产品类型
                    width = mainContentW / 15;
                    break;
                case "unitProductName"://单位产品名称
                    width = mainContentW / 9;
                    break;
                case "unitProductCode"://单位产品编号
                    width = mainContentW / 7;
                    break;
                case "productName"://产品名称
                    width = mainContentW / 9;
                    break;
                case "productCode"://产品编号
                    width = mainContentW / 7;
                    break;
                case "productStatus"://租户产品状态
                    width = mainContentW / 10;
                    break;
                // case "unitProductType":
                //     width = mainContentW / 18;
                //     break;
                // case "productInfo":
                //     width = mainContentW / 5;
                //     break;
                case "beginPeriod": //生效时间
                    width = mainContentW / 7;
                    break;
                case "expirePeriod": //失效时间
                    width = mainContentW / 7;
                    break;
                case "operation": //操作
                    width = mainContentW / 10;
                    break;
                case "unitOrgCode": //单位产品码
                    width = mainContentW / 7;
                    break;
            }
            return width;
        },

        formatNumber (n){
            n = n.toString()
            return n[1] ? n : '0' + n
        },
        // 时间格式化
        formatTime(date){
            if(!date)return;
            date = new Date(JSON.parse(date));
            let year = date.getFullYear()
            let month = date.getMonth() + 1
            let day = date.getDate()
            let hour = date.getHours()
            let minute = date.getMinutes()
            let second = date.getSeconds();
            return [year, month, day].map(this.formatNumber).join('-') + ' ' + [hour, minute, second].map(this.formatNumber).join(':')
        }
    }
};
</script>



<style lang="scss" scoped>


.operate-content{
    padding:10px 15px;
}
.disabled_text{
    color: #ccc;
    cursor: default;
}
.tenant-table{
    padding:0 10px;
    font-size: 12px;
    .viewDetail{
        color:#409EFF;
        cursor: pointer;
        font-size: 12px;
    }
}
.el-pagination{
    text-align:right;
    padding: 15px 20px;
}
.disabledCheckbox{
    .el-table{
        .el-table__header-wrapper{
            .el-checkbox{
                display: none;
            }
        }
    }
}
</style>

<style lang="scss">

.tenant-table{
    .el-table__body, .el-table__footer, .el-table__header{
        font-size: 12px;
        .el-table__row td{
            padding: 5px;
        }
    }
    .el-table th, .el-table tr.header-row{
        height:37px;
        background-color: #F5F7FA!important;
        color:#324558;
        font-size:12px;
        th.is-leaf{
            padding:0;
        }
    }
}

.el-pagination{
    background-color: #FFF;
}

// 控制弹出框样式
.detailDialog{
    .el-dialog__body{
        padding: 0 0 30px 0!important;
    }
    .el-tabs__header{
        background-color:#EDF0F6;
        padding-left: 20px;
    }
    .el-tabs--card>.el-tabs__header .el-tabs__nav{
        border:0;
    }
    .el-tabs--card>.el-tabs__header .el-tabs__item{
        margin-right:10px;
        background-color:#E2E6EE;
        color:#324558;
        font-size:12px;
        font-weight:400;
        border-radius: 3px 3px 0px 0px;
    }
    .el-tabs--card>.el-tabs__header .el-tabs__item.is-active{
        background-color:#fff;
        color:#324558;
        font-weight:500;
    }
}


</style>